#!/usr/bin/perl

# Handle a request for a Linux Counter personal registration by
# updating the database with the information and displaying
# the Linux Counter Certificate, if successful.

use strict;

use CGI::Carp;
use POSIX;
use CGI;

use Counter;
use Counter::Sendemail;
use Validate::Persons;
use Counter::Recordinfo;
use CounterCGI;
use ErrorForm;

use IsEmail qw(isemail $notemailbecause);

use vars qw($logprefix);

chdir($ENV{COUNTER_ROOT});

$logprefix = "logs";

eval "dotheregistration()";
warn "Result of registration: $@\n" if $@;

sub dotheregistration {

    my %entry;
# Get the input
my $q = new CGI;



for my $name ($q->param()) {
    $entry{$name} = $q->param($name);
}


open(DEBUGLOG, ">>$logprefix/debuglog") || warn "Unable to open $logprefix/debuglog\n";
open(EVENTLOG, ">>$logprefix/eventlog") || warn "Unable to open $logprefix/eventlog\n";
my $date = scalar(gmtime);
print EVENTLOG scalar(gmtime), " person-counter.pl\n";

# Register user
my $users = Counter::open(O_RDWR|O_CREAT);
my $persons = Counter::openfile("persons");

my $email = $entry{sendreplyto};
if (!&isemail($email)) {
    print EVENTLOG ">>>> Illegal email $email: $notemailbecause\n";
    &errorForm("illegal email", $email, $notemailbecause);
}
$email =~ tr/A-Z/a-z/; # normalize
my $user = $users->getbykey("email", $email);
if ($user) {
    print EVENTLOG ">>>> Old key for $email: ", $user->key, "\n";
    &errorForm("duplicate email", $email);
}
# Now we decide we've got an honest-to-goodness registration.
# Note the slackness of this checking :-(
print DEBUGLOG "Creating user\n";
while (1) {
    $user = $users->newnum();
    warn "Got user record ", $user->key, "\n";
    warn "Userrec->stored is ", $user->stored(), "\n";
# HIGH DEBUG: Something occasionally goes wrong here...
    if ($user->stored() ne "placeholder") {
	warn "$$: newnum did not return a placeholder";
	sleep 10;
    } else {
	last;
    }
} 
my $key = $user->key;
my $secret = int(100000*rand);
$user->{key} = sprintf("%s-%05d", $user->key, $secret);
$user->{email} = $email;
print EVENTLOG "userid is $key (new)\n";
$user->{logintime} = strftime "%Y-%m-%d %H:%M:%S", gmtime();
addadmin($user);
$user->store;
print DEBUGLOG "Creating person, key is $key\n";
delete $entry{sendreplyto};
my $person = $persons->get($user->key, O_CREAT);
for my $name ($persons->fields) {
    if ($entry{$name}) {
	$person->{$name} = $entry{$name};
	delete $entry{$name};
    }
}
for my $name (keys(%entry)) {
    print DEBUGLOG "Unknown person field: $name\n" if $entry{$name};
}

addadmin($person);
$person->store;
# Send the key and the confirimation
Counter::Sendemail::sendemail($key, undef, $email);
# Welcome the new user into town!

my $logincookie = CounterCGI::logincookie($user, $q);

print <<EoF;
Content-type: text/html; charset="utf-8"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Set-Cookie: $logincookie

<html>
EoF
CounterCGI::pagehead("Person registration accepted");
    print "<body bgcolor=\"white\">\n";
CounterCGI::pagetop($q);
print <<EoF;
<H1><img src="/cgi-bin/certificate.cgi/$key">Person registration accepted</H1>

Thanks for filling out the registration form.
<p>
You are registered Linux user number $key. The image above is your
personal registration certificate; you may want to display this on
your personal Web page.
<p>
If you do, linking it to http://counter.li.org/
will be appreciated!
EoF

CounterCGI::pagebottom();
print "\n</body>\n</html>";

} # end sub dotheregistration

# Add admin fields - recdate and method - to a record
sub addadmin {
    my $record = shift;

  Counter::Recordinfo::addadmin($record);
}
